package com.example.fy.coolweather.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.fy.coolweather.MyApplication;
import com.example.fy.coolweather.R;
import com.example.fy.coolweather.service.AutoUpdateService;
import com.example.fy.coolweather.util.HttpCallbackListener;
import com.example.fy.coolweather.util.HttpUtil;
import com.example.fy.coolweather.util.Utility;

/**
 * Created by fy on 2016/5/11.
 */
public class WeatherActivity extends BaseActivity implements View.OnClickListener{

    private static final String TAG = "WeatherActivity";
    private LinearLayout weatherInfoLayout;
    private TextView cityNameText;//城市名
    private TextView publishText;//发布时间
    private TextView weatherDespText;//天气描述
    private TextView temp1Text;//最低气温
    private TextView temp2Text;//最高气温
    private TextView currentDateText;//当前时间
    private Button switch_city;//选择城市按钮
    private Button refreshWeather;//刷新天气按钮
    private String cityName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);
        //MyHandler handler = new MyHandler();
        weatherInfoLayout = (LinearLayout)findViewById(R.id.weather_info_layout);
        cityNameText = (TextView) findViewById(R.id.city_name);
        publishText = (TextView) findViewById(R.id.publish_text);
        weatherDespText = (TextView) findViewById(R.id.weather_desp);
        temp1Text = (TextView) findViewById(R.id.temp1);
        temp2Text = (TextView) findViewById(R.id.temp2);
        currentDateText = (TextView) findViewById(R.id.current_date);
        cityName = getIntent().getStringExtra("city_name");
        if(!TextUtils.isEmpty(cityName)){
            Log.d(TAG, "onCreate: "+cityName);
            //有县级代号查询天气
            publishText.setText("同步中...");
            weatherInfoLayout.setVisibility(View.INVISIBLE);
            cityNameText.setVisibility(View.INVISIBLE);
            queryWeatherInfo(cityName);
        }else{
            //没有县级代号就显示本地天气
            showWeather();
            Log.d(TAG, "onCreate: 显示本地天气");
        }
        switch_city = (Button)findViewById(R.id.switch_city);
        switch_city.setOnClickListener(this);
        refreshWeather = (Button)findViewById(R.id.refresh_weather);
        refreshWeather.setOnClickListener(this);
    }

    /**
     * 查询天气代号对应的天气
     * @param cityName
     */
    private void queryWeatherInfo(String cityName) {
//        try{
//            Log.d(TAG, "queryWeatherInfo: "+cityName);
//            cityName = URLEncoder.encode(cityName,"utf-8");
//            Log.d(TAG, "queryWeatherInfo: "+cityName);
//        }catch (UnsupportedEncodingException e){
//            e.printStackTrace();
//        }
        String address = MyApplication.ADDRESS+cityName;
        Log.d(TAG, "queryWeatherInfo: "+address);
        HttpUtil.sendHttpRequest(address,new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                Utility.handleWeatherResponse(WeatherActivity.this,response);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showWeather();
                    }
                });
            }

            @Override
            public void onError(Exception e) {
                publishText.setText("同步失败");
            }
        });
    }

    private void showWeather() {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        cityNameText.setText(prefs.getString("city_name",""));
        temp1Text.setText(prefs.getString("temp1",""));
        temp2Text.setText(prefs.getString("temp2",""));
        weatherDespText.setText(prefs.getString("weather_desp",""));
        publishText.setText("今天"+prefs.getString("publish_time","")+"发布");
        currentDateText.setText(prefs.getString("current_date",""));
        Log.d(TAG, "showWeather: "+prefs.getString("publish_time",""));
        weatherInfoLayout.setVisibility(View.VISIBLE);
        cityNameText.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.switch_city:
                Intent intent = new Intent(this,ChooseAreaActivity.class);
                intent.putExtra("from_weather_activity",true);
                startActivity(intent);
                finish();
                break;
            case R.id.refresh_weather:
                if(cityNameText.getText().toString() != null && cityNameText.getText().toString() != ""){
                    publishText.setText("同步中...");
                    queryWeatherInfo(cityNameText.getText().toString());
                }else{
                    publishText.setText("出错了...");
                }
                break;
            default:
                break;
        }
    }
}
